package com.nbufe.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nbufe.domain.entity.CarbonStatistics;
import com.nbufe.exception.SystemException;
import com.nbufe.mapper.CarbonStatisticsMapper;
import com.nbufe.service.CarbonStatisticsService;
import com.nbufe.service.CarbonTradingService;
import com.nbufe.service.DataService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * (CarbonStatistics)表服务实现类
 *
 * @author luzhiheng
 * @since 2024-02-01 13:49:13
 */
@Service("carbonStatisticsService")
public class CarbonStatisticsServiceImpl extends ServiceImpl<CarbonStatisticsMapper, CarbonStatistics> implements CarbonStatisticsService {

    @Resource
    private DataService dataService;

    @Override
    public void updateCarbonStatistics(Double updateQuota, Double ccer) {
        Double totalCarbonEmission = dataService.queryTotalCO2();
        List<CarbonStatistics> carbonStatisticsList = this.list();
        if (CollectionUtils.isEmpty(carbonStatisticsList)) {
            CarbonStatistics carbonStatistics = new CarbonStatistics();
            carbonStatistics.setCarbonEmission(totalCarbonEmission);
            carbonStatistics.setUnpayQuota(updateQuota);
            carbonStatistics.setCcer(ccer);
            this.save(carbonStatistics);
        } else {
            CarbonStatistics statistics = carbonStatisticsList.get(0);
            statistics.setCarbonEmission(totalCarbonEmission);
            statistics.setUnpayQuota(statistics.getUnpayQuota() + updateQuota);
            statistics.setCcer(statistics.getCcer() + ccer);
            this.updateById(statistics);
        }
    }

    @Override
    public double getNeedPayQuota() {
        List<CarbonStatistics> carbonStatisticsList = this.list();
        if (CollectionUtils.isEmpty(carbonStatisticsList)) {
            throw new SystemException("碳统计不存在");
        }
        CarbonStatistics statistics = carbonStatisticsList.get(0);
        Double totalCO2 = dataService.queryTotalCO2();
        double needPay = totalCO2 - (statistics.getUsedQuota() + statistics.getUsedCcer());
        if (needPay <= 0) {
            return 0;
        }
        return needPay;
    }

}
